package org.example.handler;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.example.constant.ResponseCode;
import org.example.exception.GlobalException;
import org.example.util.JsonResult;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理类
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理GlobalException
     * @param e
     * @param response
     * @return
     */
    @ExceptionHandler
    public JsonResult<Void> handleGlobalException(GlobalException e, HttpServletResponse response) {
        printMessage(e);
        response.setStatus(e.getResponseCode().getValue());
        return JsonResult.error(e.getResponseCode(), e);
    }

    /**
     * 处理AuthenticationException
     * @param e
     * @return JsonResult<Void>
     */
    @ExceptionHandler
    @ResponseStatus(HttpStatus.FORBIDDEN)
    public JsonResult<Void> handleAuthenticationException(AuthenticationException e) {
        printMessage(e);
        return JsonResult.error(ResponseCode.FORBIDDEN, e);
    }

    /**
     * 打印异常信息
     * @param e Exception
     */
    private void printMessage(Exception e) {
        String message = e.getMessage();
        log.error(message);
        e.printStackTrace();
    }
}
